import { useLayoutUpdateEffect } from '@/utils/hooks/useLayoutUpdateEffect';
import { DownOutlined } from '@ant-design/icons';
import {
  Checkbox,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Space,
} from 'antd';
import React, { useCallback, useMemo, useRef, useState } from 'react';
import Submitter from './Submitter';
import { QueryFilterContentProps, ValueTypeProps } from './interface';
const { RangePicker } = DatePicker;

const InputRange = ({ value = [null, null], onChange, ...restProps }: any) => {
  // 输入值改变
  const handleInput = (curValue: string | number | null, type: string) => {
    const nValue = [...value];
    if (type === 'prev') {
      nValue[0] = curValue;
    }
    if (type === 'next') {
      nValue[1] = curValue;
    }
    onChange(nValue);
  };

  return (
    <div className="ym-query-filter-input-range">
      <InputNumber
        value={value?.[0]}
        {...restProps}
        onChange={(curValue) => handleInput(curValue, 'prev')}
      />
      <span>&nbsp;~&nbsp;</span>
      <InputNumber
        value={value?.[1]}
        {...restProps}
        onChange={(curValue) => handleInput(curValue, 'next')}
      />
    </div>
  );
};

const QueryFilterContent: React.FC<QueryFilterContentProps> = (props) => {
  const {
    prefixCls,
    spanSize,
    onCollapsed,
    defaultCollapsed,
    collapsed,
    operColPosition,
    submitter,
    hiddenReset = false,
    formItems,
    formItemFixStyle,
    queryFilterFormInstance,
    searchGutter = [24, 24],
    showHiddenNum = false,
    collapseRender,
  } = props;

  const [mergeCollapsed, setMergeCollapsed] = useState(() => {
    if (collapsed !== undefined) {
      return collapsed;
    } else {
      return !!defaultCollapsed;
    }
  });

  //第一次不执行
  useLayoutUpdateEffect(() => {
    setMergeCollapsed(!!collapsed);
  }, [collapsed]);

  // 计算出所有列（操作列除外)所占格子数
  const totalSpanRef = useRef<number>(0);

  // 当前展开列（操作列除外）所有列所占格子数
  const currentSpanRef = useRef<number>(0);

  const renderSearchComp = useCallback(
    ({
      valueType,
      children,
    }: {
      valueType?: ValueTypeProps;
      children?: React.ReactNode;
    }) => {
      if (children) {
        return children;
      }
      const {
        type,
        inputProps,
        inputRangeProps,
        inputNumberProps,
        datePickerProps,
        rangePickerProps,
        selectProps,
        checkboxProps,
        radioGroupProps,
      } = valueType || {};
      switch (type) {
        case 'input':
          return <Input {...inputProps} />;
        case 'inputRange':
          return <InputRange {...inputRangeProps} />;
        case 'inputNumber':
          return <InputNumber {...inputNumberProps} />;
        case 'date':
          return <DatePicker {...datePickerProps} />;
        case 'rangeDate':
          return <RangePicker {...rangePickerProps} />;
        case 'select':
          return <Select {...selectProps} />;
        case 'checkbox':
          return <Checkbox.Group {...checkboxProps} />;
        case 'radio':
          return <Radio.Group {...radioGroupProps} />;
        default:
          return <Input placeholder="请输入" {...inputProps} />;
      }
    },
    [],
  );

  const domsDetail: { doms: any[]; hiddenNum: number } | undefined =
    useMemo(() => {
      if (!spanSize.span) return;
      // console.log('--QueryFilterContent--spanSize--:', spanSize);
      totalSpanRef.current = 0;
      currentSpanRef.current = 0;

      const processedList = formItems
        .filter((item) => !item.hidden)
        .map((item, index) => {
          const colSpan = Math.min(item.colProps?.span || spanSize.span!, 24); //spanSize.span:当前宽度下,一行默认每列所占格栅数（最多只能取24）
          // 计算总的 totalSpan 长度
          totalSpanRef.current += colSpan; //格栅数 (操作列格栅数量占比数：colSpan)
          const {
            label,
            name,
            valueType,
            children,
            colProps,
            ...restFormItemProps
          } = item;
          const itemDom = renderSearchComp({ valueType, children });
          const calItemProps = {
            ...restFormItemProps,
            ...formItemFixStyle,
            name,
            label,
            key: name,
          };
          const formItemDom = (
            <Form.Item {...calItemProps}>{itemDom}</Form.Item>
          );
          //----
          // const hidden = mergeCollapsed && totalSpan >= 24 ? true : false;
          // 累加格栅数 > 24 - 操作列所占格栅数
          const hidden =
            mergeCollapsed && totalSpanRef.current > 24 - spanSize.span!
              ? true
              : false;

          if (React.isValidElement(itemDom) && hidden) {
            return {
              formItemDom: React.cloneElement(formItemDom, {
                hidden: true,
              }),
              hidden: true,
              colSpan,
            };
          }

          return {
            formItemDom,
            colSpan,
            hidden: false,
          };
        });

      const tempDoms = processedList?.map((itemProps, index) => {
        const { formItemDom, colSpan, hidden } = itemProps;
        if (hidden) return formItemDom;
        //当前行剩下的格子数: 24 - (currentSpan % 24)   ， （currentSpan % 24）: 当前行已经占据的格栅数 20%24 === 20
        if (24 - (currentSpanRef.current % 24) < colSpan) {
          //全部展开情况下
          // 如果当前行空余位置放不下,那就加上空余位置刚好凑成一整行(24的倍数)，再折行
          totalSpanRef.current += 24 - (currentSpanRef.current % 24);
          currentSpanRef.current += 24 - (currentSpanRef.current % 24);
        }

        currentSpanRef.current += colSpan;
        return (
          <Col key={index} span={colSpan}>
            {formItemDom}
          </Col>
        );
      });

      const hiddenNum = showHiddenNum
        ? processedList?.filter((item) => item.hidden).length
        : 0;

      return {
        doms: tempDoms,
        hiddenNum,
      };
    }, [formItems, spanSize.span, mergeCollapsed, showHiddenNum]);

  /** 是否需要展示 collapseRender */
  const needCollapseRender = useMemo(() => {
    if (totalSpanRef.current < 24) {
      return false;
    }
    return true;
  }, [totalSpanRef.current]);

  // operationColPosition
  const offset = useMemo(() => {
    if (operColPosition === 'inline') return 0;
    const offsetSpan = Math.min(
      (currentSpanRef.current % 24) + (spanSize.span || 0),
      24,
    ); //  (currentSpanRef.current % 24): 当前行(最后一行) children 已经占据的格栅数，+ spanSize.span：当前行操作列占据的格栅数
    return 24 - offsetSpan;
  }, [currentSpanRef.current, spanSize.span]);

  return (
    <Row
      gutter={searchGutter}
      className={`${prefixCls}-row`}
      justify="start"
      key="resize-observer-row"
    >
      {domsDetail && domsDetail.doms}
      <Col
        key="submitter"
        span={spanSize.span}
        offset={offset}
        style={{
          textAlign: operColPosition === 'inline' ? 'start' : 'end',
        }}
      >
        <Form.Item label=" " colon={false} style={{ margin: 0 }}>
          <Space direction="horizontal">
            <Submitter
              queryFilterFormInstance={queryFilterFormInstance}
              submitter={submitter}
              hiddenReset={hiddenReset}
            />
            {needCollapseRender && (
              <a
                className={`${prefixCls}-collapse-btn`}
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                  if (collapsed === undefined) {
                    setMergeCollapsed(!mergeCollapsed);
                  }
                  onCollapsed?.(!mergeCollapsed);
                }}
              >
                {typeof collapseRender === 'function' ? (
                  collapseRender?.(mergeCollapsed, domsDetail?.hiddenNum)
                ) : (
                  <DownOutlined
                    style={{
                      transition: '0.3s all',
                      transform: `rotate(${mergeCollapsed ? 0 : 0.5}turn)`,
                    }}
                  />
                )}
              </a>
            )}
          </Space>
        </Form.Item>
      </Col>
    </Row>
  );
};

export default QueryFilterContent;
